let limitConnect = 3;
let timeConnect = 0;
let timerWs = null;

let Socket = "";
// 缓存ip
let ip = "";
/**
 * 建立websocket连接
 * @param {string} url ws地址
 */
export const createSocket = (url) => {
  ip = url;
  Socket = new WebSocket(url);
  // 发送心跳
  Socket.onopen = onopenWS;
  // 接收消息
  Socket.onmessage = onmessageWS;
  // 断开重连
  Socket.onclose = oncloseWS;
};

// 断开连接
export const closeSoket = () => {
  if (Socket.readyState === 1) {
    Socket.close();
    Socket = null;
  }
};

/** 打开WS之后发送心跳 */
const onopenWS = () => {
  sendPing();
};

/** WS数据接收统一处理 （通过事件订阅处理）*/
const onmessageWS = (e) => {
  console.log(e);
  window.dispatchEvent(
    new CustomEvent("onmessageWS", {
      detail: {
        data: e.data,
      },
    })
  );
};

/** 断开重连 */
const oncloseWS = () => {
  reconnectWs();
};
/**
 * @description 重连机制
 */
const reconnectWs = () => {
  if (limitConnect > 0) {
    limitConnect--;
    timeConnect++;
    console.log(`第${timeConnect}次重连`);
    setTimeout(() => {
      createSocket(ip);
    }, 2000);
  } else {
    console.log("webSocket连接超时");
  }
};

/**
 * 发送数据
 * @param {any} message 需要发送的数据
 */
export const sendWSPush = (message) => {
  return new Promise((reslove, reject) => {
    Socket.send(JSON.stringify(message));
    reslove(Socket.readyState);
  });
};

/** 发送心跳
 * @param {number} time 心跳间隔毫秒10s 默认5min=5*60s 1s=1000ms
 * @param {string} ping 心跳名称 默认字符串ping
 */
export const sendPing = (
  time = 1000,
  ping = JSON.stringify({ code: "WEB_SET_DADIAN", data: "" })
) => {
  if (timerWs) {
    clearInterval(timerWs);
    timerWs = null;
  }
  timerWs = setInterval(() => {
    Socket.send(ping);
  }, time);
};

// Socket.readyState状态码：0:正在连接；1:连接成功，可以通信  2：表示连接正在关闭 3：表示连接已经关闭，或者打开连接失败
